from app import ma
from .models import Ingredient, Nutrition

# 1. 简化版食材 Schema（无嵌套，依赖最少，优先定义）
class IngredientSimpleSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Ingredient
        load_instance = True  # 允许反序列化为模型实例
        fields = ('id', 'name', 'category', 'unit')  # 明确指定需要序列化的字段，确保包含食材名称

# 实例化简化版序列化器
ingredient_simple_schema = IngredientSimpleSchema()
ingredients_simple_schema = IngredientSimpleSchema(many=True)

# 2. 营养成分 Schema（核心：用字符串引用 RecipeSimpleSchema，延迟解析）
class NutritionSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Nutrition
        load_instance = True
        # 让Marshmallow自动发现所有字段，避免版本兼容性问题
    
    # 【关键修复】用完整模块路径字符串引用，避免直接导入触发循环
    recipe = ma.Nested('app.recipes.schemas.RecipeSimpleSchema', many=False)

# 实例化营养成分序列化器
nutrition_schema = NutritionSchema()
nutritions_schema = NutritionSchema(many=True)

# 3. 完整食材 Schema（嵌套 NutritionSchema，无循环依赖）
class IngredientSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Ingredient
        load_instance = True
        # 让Marshmallow自动发现所有字段，避免版本兼容性问题
    
    # 嵌套已定义的 NutritionSchema，无新依赖
    nutrition = ma.Nested(NutritionSchema, many=False)

# 实例化完整食材序列化器
ingredient_schema = IngredientSchema()
ingredients_schema = IngredientSchema(many=True)